package com.ztmg.water.service.water.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ztmg.common.constant.CommonConstants;
import com.ztmg.common.constant.ErrorConst;
import com.ztmg.common.util.DateUtil;
import com.ztmg.common.util.HttpClientUtils.HttpClientUtils;
import com.ztmg.common.util.handleSign.Base64;
import com.ztmg.common.util.handleSign.SignatureUtil;
import com.ztmg.common.util.resultUtils.JsonResult;
import com.ztmg.water.dto.water.RefundInfoDTO;
import com.ztmg.water.dto.water.RefundInfoPageDTO;
import com.ztmg.water.mapper.base.DepositRecordMapper;
import com.ztmg.water.mapper.student.StudentTicketMapper;
import com.ztmg.water.mapper.water.RefundInfoMapper;
import com.ztmg.water.model.base.DepositRecord;
import com.ztmg.water.model.water.RefundInfo;
import com.ztmg.water.model.water.RefundInfoExample;
import com.ztmg.water.service.water.RefundInfoService;
import com.ztmg.water.vo.water.RefundInfoVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class RefundInfoServiceImpl implements RefundInfoService {

    @Resource
    private RefundInfoMapper refundInfoMapper;
    @Resource
    private StudentTicketMapper  studentTicketMapper;
    @Resource
    private DepositRecordMapper depositRecordMapper;
    @Override
    public JsonResult create(RefundInfoDTO dto) {
        if(null != dto){
            RefundInfo bean = new RefundInfo();
            BeanUtils.copyProperties(dto,bean);
            bean.setCreateTime(new Date());
            //后续完善
            bean.setCreater("");
            refundInfoMapper.insert(bean);
            return JsonResult.success();
        }else {
            return JsonResult.fail(ErrorConst.SYSTEM_PARM_ERROR,ErrorConst.SYSTEM_PARM_ERROR_MSG);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public JsonResult update(RefundInfoDTO dto) {
        if(null != dto && null != dto.getId()){
            RefundInfo bean = new RefundInfo();
            BeanUtils.copyProperties(dto,bean);
            bean.setModifyTime(new Date());
            //后续完善
            bean.setModifier("");
            refundInfoMapper.updateByPrimaryKeySelective(bean);

            RefundInfo refundInfo = refundInfoMapper.selectByPrimaryKey(dto.getId());

            //当修改为拒绝申请时，把对应的学生水票返回给学生
            if(dto.getStatus() == 3)
            {

                Map<String,String> params = new HashMap<>();
                if(dto.getRefundType() == 0)
                {
                    params.put("studentId",String.valueOf(refundInfo.getStudentId()));
                    params.put("ticketId",String.valueOf(refundInfo.getRefundObjId()));
                    params.put("ticketNum",refundInfo.getRefundObjNums().toString());
                    params.put("modifier","");
                    params.put("modifyTime",DateUtil.parseDateToStr(new Date(),DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
                    studentTicketMapper.updateTicketNums(params);
                }else
                 if (dto.getRefundType() == 1)
                {
                    DepositRecord record = new DepositRecord();
                    record.setModifier("");
                    record.setModifyTime(new Date());
                    record.setDepostObjId(refundInfo.getStudentId());
                    record.setDepositInfoObjId(refundInfo.getRefundObjId());
                    record.setDepostReturnNum(refundInfo.getRefundObjNums());
                    depositRecordMapper.updateRecordByStudentIdAndWaterId(record);
                }

            }else{
                String [] refundTypeString = {"ticket","deposit"};
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("username","admin");
                jsonObject.put("password","123456");
                jsonObject.put("member_id",refundInfo.getStudentId());
                jsonObject.put("sn",refundInfo.getRefundSn());
                jsonObject.put("money",refundInfo.getTotalMoney());
                jsonObject.put("type",refundTypeString[refundInfo.getRefundType()]);
                String data = JSON.toJSONString(jsonObject);
                String params= "";
                try {
                    byte[] encrypt = SignatureUtil.signByPub(data.getBytes("utf-8"),Base64.decode(CommonConstants.PHP_PUBLIC_KEY),"RSA");
                    params = "data="+URLEncoder.encode(Base64.encode(encrypt), "UTF-8");
                } catch (GeneralSecurityException e) {
                    return JsonResult.fail(ErrorConst.SIGN_FAILTURE,ErrorConst.SIGN_FAILTURE_MSG);
                } catch (UnsupportedEncodingException e) {
                    return JsonResult.fail(ErrorConst.BASE64_FAILTURE,ErrorConst.BASE64_FAILTURE_MSG);
                }
                 HttpClientUtils.sendPost(CommonConstants.SEND_MESSAGE_URL,params);
            }
            return JsonResult.success();
        }else {
            return JsonResult.fail(ErrorConst.SYSTEM_PARM_ERROR,ErrorConst.SYSTEM_PARM_ERROR_MSG);
        }
    }

    @Override
    public JsonResult<RefundInfoVO> selectById(Integer id) {
        if(null != id){
            RefundInfo bean = refundInfoMapper.selectByPrimaryKey(id);
            RefundInfoVO vo = new RefundInfoVO();
            if(null != bean){
                BeanUtils.copyProperties(bean,vo);
            }else {
                return JsonResult.fail(ErrorConst.SYSTEM_PARM_ERROR,ErrorConst.SYSTEM_PARM_ERROR_MSG);
            }
            return JsonResult.success(vo);
        }else{
            return JsonResult.fail(ErrorConst.SYSTEM_PARM_ERROR,ErrorConst.SYSTEM_PARM_ERROR_MSG);
        }
    }

    @Override
    public JsonResult<List<RefundInfoVO>> select(RefundInfoDTO dto) {
        RefundInfoExample example = new RefundInfoExample();
        RefundInfoExample.Criteria criteria =  example.createCriteria();
        /***
         * 根据具体的业务，查询条件赋值
         */
        List<RefundInfo> sysUserList =refundInfoMapper.selectByExample(example);
        List<RefundInfoVO> respDTOS = sysUserList.parallelStream().map((bean) -> {
            RefundInfoVO vo = new RefundInfoVO();
            BeanUtils.copyProperties(bean, vo);
            return vo;
        }).collect(Collectors.toList());

        return JsonResult.success(respDTOS);
    }

    @Override
    public JsonResult<PageInfo<RefundInfoVO>> selectPage(RefundInfoPageDTO dto) {
        RefundInfoExample example = new RefundInfoExample();
        RefundInfoExample.Criteria criteria =  example.createCriteria();
        RefundInfoExample.Criteria criteria1 =  example.createCriteria();
        if(null!=dto.getSearchKey() && !"".equals(dto.getSearchKey()))
        {
            criteria.andStudentNameLike(dto.getSearchKey());
            criteria1.andRefundSnLike(dto.getSearchKey());
        }
        if(null!=dto.getRefundType() && !dto.getRefundType().equals(""))
        {
            criteria.andRefundTypeEqualTo(dto.getRefundType());
        }
        /***
         * 根据具体的业务，查询条件赋值
         */
        PageHelper.startPage(dto.getPage(), dto.getLimit());
        List<RefundInfo> beanList = refundInfoMapper.selectByExample(example);
        PageInfo pageInfo = new PageInfo<>(beanList);
        List<RefundInfoVO> respDTOS = beanList.parallelStream().map((bean) -> {
            RefundInfoVO vo = new RefundInfoVO();
            BeanUtils.copyProperties(bean, vo);
            return vo;
        }).collect(Collectors.toList());
        pageInfo.setList(respDTOS);
        return JsonResult.success(pageInfo);
    }

    @Override
    public JsonResult deleteById(Integer id) {
            return JsonResult.success( refundInfoMapper.deleteByPrimaryKey(id));
    }

    @Override
    public JsonResult delete(RefundInfoDTO dto) {
            RefundInfoExample example = new RefundInfoExample();
            RefundInfoExample.Criteria criteria =  example.createCriteria();
            /***
             * 根据具体的业务，查询条件赋值
             */
            return JsonResult.success(refundInfoMapper.deleteByExample(example));
    }
}
